<?php


namespace app\admin\controller;


use  \think\facade\Cache;
use think\Db;
use think\Exception;
use think\facade\Log;
use think\Request;
use think\Validate;

class LoginController extends CommonController
{
    private static $USER_TABLE="user";


    public function Login(Request $request)
    {
        $res= $request->param();
        $rule = [
            'account'  => 'require',
            'password'   => 'require',
        ];
        $message  = [
            'account.require' => '账号不能为空～',
            'password.require' => '密码必填～',
        ];
        $validate = Validate::make($rule,$message);
        $result = $validate->check($res);
        if(!$result) {
            return returnFail($validate->getError());
        }
        $is_set=Db::table(self::$USER_TABLE)
            ->where('account','=',$request->post('account'))
            ->where('status','=',0)
            ->where('delete_flag','=',0)
            ->field('salt,password,id')
            ->select();
        if (!$is_set){
            return  returnFail('账号不存在');
        }
        $pass='lan'.$request->post('password').$is_set[0]['salt'];
        if (password_verify($pass, $is_set[0]['password'])){
            //登陆成功 生成token
            $jwtAuth =JwtAuth::getInstance();
            $token = $jwtAuth->setUid($is_set[0]['id'])->encode()->getToken();
            try {
                Db::startTrans();
                $now=date('Y-m-d H:i:s',time());
                Db::table(self::$USER_TABLE)->where('id','=',$is_set[0]['id'])->update(['login_time'=>$now,'token'=>$token,'update_by'=>$is_set[0]['id'],'update_time'=>$now]);
                Db::commit();
                return returnSuccess(['token'=>$token],'登陆成功');
            }catch (Exception $e){
                Db::rollback();
                return returnFail('账号或密码错误');
            }

        }else{
            return returnFail('账号或密码错误');
        }

    }

    public function getUserInfo(Request $request){
        $res=$request->post('token');
        if (!$res){
            return returnFail('参数错误');
        }
        $info = DB::table(self::$USER_TABLE)
            ->where('delete_flag','=',0)
            ->where('status','=',0)
            ->where('token','=',$res)
            ->field('id,account,ava_url,info')
            ->select();
        $info[0]['roles']=$this->GetPermissionInfo($info[0]['id']);
        return returnSuccess($info,'success');
    }

    public function GetPermissionInfo($id){
//        $id= $request->get('id');
        $res= $this->GetPermissionUser($id);
        if (!empty($res)){
            foreach ($res as $k=>$v) {
                $arr=['title'=>$v['per_title'],'icon'=>$v['per_icon']];
                $res[$k]['meta']=$arr;
            }
        }
        $res=$this->PermissionTree($res);
        return $res;
    }
    public function PermissionTree($data,$pid = 0){
        $children = [];   // 定义存储子级数据数组
        foreach ($data as $key => $value) {
            if ($value['p_id'] == $pid) {
                unset($data['$key']);  // 使用过后可以销毁
                $value['children'] = $this->PermissionTree($data,$value['per_id']);   // 递归调用，查找当前数据的子级
                $children[] = $value;   // 把子级数据添加进数组
            }
        }
        return $children;
    }

    public function LoginOut(){
        Cache::clear();
        return returnJson(LOGIN_OUT_CODE,[],'验证过期请重新登陆');
    }

}